/*
 * @LastEditors: YuSeen 2290515673@qq.com
 * @LastEditTime: 2022-08-21 15:41:19
 */
import Message from "@/components/message/message";
import { usePlayStore } from "@/store/play";
import {
  getMusicUrl,
  getMusicDetail,
  getMusicLyric,
} from "@/service/api/song/song";
import { getSongListSongs } from '@/service/api/songList/songList'
import { playMode } from "@/types/store/playStoreType";
import { random } from 'lodash'

export interface ILyricItem {
  //歌词项
  text: string;
  time: number;
  index: number;
}

export const usePlay = () => {

  const playStore = usePlayStore();
  // 播放歌曲
  const playMusic = async (id: number) => {
    try {

      playStore.setId(id);
      const [urlRes, detailRes, lyricRes] = await Promise.all([
        getMusicUrl(id),
        getMusicDetail(id),
        getMusicLyric(id),
      ]);
      playStore.setUrl(urlRes.data[0].url);
      playStore.toggleIsPlaying(true);
      playStore.setDetail(detailRes.songs[0]);
      playStore.setLyric(lyricRes.lrc.lyric);
    } catch (error) {
      Message.error(error as string);
      console.log("错误", error);
    }
  };

  // 传入歌单id，播放整个歌单
  const playSongList = async (songListId: number) => {
    const { songs } = await getSongListSongs(songListId)
    playStore.setPlayList(songs)
    playMusic(songs[0].id)
  }

  // 播放下一首
  const playNextMusic = () => {
    // 当前的歌曲id
    const currentId = playStore.songId as number
    // 当前歌曲在播放列表中的索引
    const index = playStore.playList.findIndex(item => item.id === currentId)
    // 当前播放模式
    const currentPlayMode = playStore.playMode
    // 顺序播放的方法
    const loopPlay = () => {
      let musicId = currentId
      if(index === playStore.playList.length - 1) {
        musicId = playStore.playList[0].id
      } else {
        musicId = playStore.playList[index + 1].id
      }
      playMusic(musicId)
      setPLayHistory(musicId)
    }
    // 随机播放的方法
    const randomPlay = ()  => {
      const id = playStore.playList[random(0, playStore.playList.length - 1)].id
      playMusic(id)
      setPLayHistory(id)
    }
    switch (currentPlayMode) {
      case playMode.单曲循环:
        playMusic(currentId)
        setPLayHistory(currentId)
        break
      case playMode.顺序播放:
        loopPlay()
        break
      case playMode.随机播放:
        randomPlay()
        break
    }
  }
  
  // 设置播放记录
  const setPLayHistory = (musicId: number) => {
    const historyList = playStore.playHistory
    // 如果最新的一条就是当前的歌曲，则不进行添加,直接返回
    if(historyList[historyList.length - 1] === musicId) return;
    // 长度超出50，删除最旧的一条数据
    if(historyList.length === 50) historyList.shift()
    // 历史中已存在，则将其删除
    if(historyList.includes(musicId)) historyList.splice(historyList.indexOf(musicId), 1)
    historyList.push(musicId)
    playStore.setPlayHistory(historyList)
  }

  // 播放上一首
  const playLastMusic = () => {
    const len = playStore.playHistory.length
    if(len === 0) return Message.error('暂无播放记录')
    const currentId = playStore.songId as number
    const currentIndex = playStore.playHistory.indexOf(currentId)
    if(currentIndex === 0) {
      playMusic(playStore.playHistory[len - 1])
    } else {
      playMusic(playStore.playHistory[currentIndex - 1])
    }
  }

  // 获取歌词时间对象
  const getLyricObj = (lyric: string) => {
    const lyricObj: ILyricItem[] = [];
    const lineTimeReg = /\[(\d{2}):(\d{2}).(\d{2,3})]/g; //歌词时间提取正则
    // 时间格式化
    const transformRegTime = (timeArr: any) => {
      timeArr = timeArr.map((item: any, index: number) => {
        if (index >= 1 && index <= 3) return parseInt(item);
        return item;
      });
      return timeArr[1] * 60 * 1000 + timeArr[2] * 1000 + timeArr[3];
    };
    lyric.split("\n").forEach((item, index) => {
      const time = lineTimeReg.exec(item);
      if (!time) return;
      const text = item.replace(lineTimeReg, "");
      if (text === "") return;
      lyricObj.push({
        time: transformRegTime(time),
        text,
        index,
      });
    });
    return lyricObj;
  };

  // 二分法查找,传入歌词数组和当前的播放时间，获取对应的歌词
  const getCurLyric = (arr: ILyricItem[], target: number): ILyricItem => {
    const end = arr.length - 1;
    if (arr[0].time >= target) return arr[0];
    if (arr[end].time <= target) return arr[end];
    const midIndex = Math.floor((arr.length - 1) / 2);
    const midTime = arr[midIndex].time;
    if (midTime <= target && arr[midIndex + 1].time > target) return arr[midIndex]
    if (midTime > target) return getCurLyric(arr.slice(0, midIndex), target);
    if (midTime < target) return getCurLyric(arr.slice(midIndex, end), target);
    return arr[0];
  };

  return {
    getLyricObj,
    playSongList,
    playMusic,
    getCurLyric,
    playLastMusic,
    playNextMusic
  };
};
